#include <stdio.h>
#include <error.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
#include <unistd.h>
#include <string.h>
#include <stdlib.h>
#include <sys/types.h>
#include <dirent.h>
#include <errno.h>
#include <time.h>

int get_time(char *t,int len)
{
	time_t          rawtime;
	struct tm      *timeinfo = NULL;
	if(!t || 0 == len)
	{
		return -1;
	}

	//时间读取
	time(&rawtime);
	timeinfo = localtime(&rawtime);
	snprintf(t,len,"%d/%d/%d/%d:%d:%d",timeinfo->tm_year+1900,timeinfo->tm_mon+1,timeinfo->tm_mday,timeinfo->tm_hour,timeinfo->tm_min,timeinfo->tm_sec);
	return 0;

}
int get_temperature(float *T)
{
	int              fd = -1;
	char             buf[128];
	char            *temp = NULL;
	DIR             *dirp = NULL;
	struct dirent   *direntp = NULL;
	char             chip_sn[32];
	char             w1_path[68] ="/sys/bus/w1/devices/";
	int              found = 0;

	if(!T)
	{
		return -1;
	}

	//温度读取
	dirp = opendir(w1_path);
	if(!dirp)
	{
		printf("open folder %s failure:%s\n",w1_path,strerror(errno));
		return -1;
	}

	while(NULL != (direntp = readdir(dirp)))
	{
		if((strstr(direntp->d_name,"28-")))
		{
			strncpy(chip_sn,direntp->d_name,sizeof(chip_sn));
			found = 1;
		}
	}
	closedir(dirp);
    
	if(!found)
	{
		printf("can not find ds18b20 chipset!");
		return -2;
	}

	strncat(w1_path,chip_sn,sizeof(w1_path)-strlen(w1_path));
	strncat(w1_path,"/w1_slave",sizeof(w1_path)-strlen(w1_path));

	fd = open(w1_path,O_RDONLY);
	if(fd < 0)
	{
		printf("open file failure:%s\n",strerror(errno));
		close(fd);
		return -3;
	}

	memset(buf,0,sizeof(buf));
	if(read(fd,buf,sizeof(buf)) < 0)
	{
		printf("read data from fd=%d failure:%s\n",fd,strerror(errno));
		close(fd);
		return -4;
	}
	temp = strstr(buf,"t=");
	temp += 2;
	*T = atof(temp)/1000;
	close(fd);
}
